package com.embedsky.administrator.mycardemulation.socket;

import android.util.Log;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class ByteUtil {
    private static final int CMD_HEAD = 4;
    /**
     * @return packed bytes
     * @Des: pack bytes as a data package
     * 0xFF 0xF6 len(2bytes) + content
     */
    public static byte[] packBytes(byte[] bytes) {
        byte[] retBytes = new byte[bytes.length + CMD_HEAD];
        retBytes[0] = (byte) 0xFF;
        retBytes[1] = (byte) 0xF6;
        retBytes[2] = (byte) (bytes.length >> 8);
        retBytes[3] = (byte) bytes.length;
        for (int i = 0; i < bytes.length; i++) {
            retBytes[CMD_HEAD + i] = bytes[i];
        }
        Log.d("ByteUtil", "packBytes: " + Arrays.toString(retBytes));
        return retBytes;
    }

    /**
     * @return packed bytes of heart
     * @Des: pack bytes as a data package
     * 0xFF 0xF7 0xE8 0x10
     */
    public static byte[] packHeartBytes() {
        byte[] retBytes = new byte[CMD_HEAD];
        retBytes[0] = (byte) 0xFF;
        retBytes[1] = (byte) 0xF7;
        retBytes[2] = (byte) 0xE8;
        retBytes[3] = (byte) 0x10;
        return retBytes;
    }

    /**
     * @return list of bytes
     * @Des: parse bytes one by one
     */
    public static List<byte[]> parseBytes(byte[] bytes, IOnHeardBeatListener listener) {
        List<byte[]> retList = new ArrayList<>();
        parseOne(bytes, retList, listener);
        return retList;
    }

    private static void parseOne(byte[] bytes, List<byte[]> retList, IOnHeardBeatListener listener) {
        Log.d("TAG", "parseOne: " + Arrays.toString(bytes));
        if (bytes.length < CMD_HEAD) {
            return;
        }
        if (bytes[0] == (byte) 0xFF && bytes[1] == (byte) 0xF6) {
            int len = (bytes[2] & 0xFF) << 8 | (bytes[3] & 0xFF);
            if (bytes.length < len + CMD_HEAD) {
                return;
            }
            byte[] temp = new byte[len];
            if (len == CMD_HEAD) {
                if (bytes[4] == (byte) 0xFF && bytes[5] == (byte) 0xF7
                        && bytes[6] == (byte) 0xE8 && bytes[7] == (byte) 0x10) {
                    listener.onHeardBeat();
                }
            } else {
                for (int i = 0; i < len; i++) {
                    temp[i] = bytes[CMD_HEAD + i];
                }
                retList.add(temp);
            }
            int lastLen = len + CMD_HEAD;
            if (lastLen < bytes.length) {
                byte[] temps = new byte[bytes.length - lastLen];
                for (int i = 0; i < temps.length; i++) {
                    temps[i] = bytes[i + lastLen];
                }
                parseOne(temps, retList, listener);
            }
        }
    }
}
